import requests
import json
import time
import hashlib

class LeaseVerifyApi:
    """
    租赁验证API
    用于发送租赁验证请求
    """
    
    def __init__(self, auth_token=None, uk=None, device_id=None):
        """
        初始化API
        
        Args:
            auth_token: 授权令牌，格式为"Bearer xxx..."
            uk: 设备UK值
            device_id: 设备ID，如果不提供则自动生成
        """
        self.base_url = "https://api.youpin898.com"
        self.api_path = "/api/youpin/bff/order/lease/user/send-verify"
        self.auth_token = auth_token
        self.uk = uk
        
        # 如果提供了设备ID，则使用提供的设备ID
        if device_id:
            self.device_id = device_id
        else:
            self.device_id = ""
        
    def _generate_request_tag(self):
        """生成请求标签"""
        # 简单实现，实际可能更复杂
        timestamp = str(int(time.time() * 1000))
        md5 = hashlib.md5()
        md5.update(timestamp.encode('utf-8'))
        return md5.hexdigest().upper()
    
    def send_verify(self, commodity_no, raise_on_error=False):
        """
        发送租赁验证请求（风格统一，详细日志、异常友好、兼容code/Code）
        Args:
            commodity_no: 商品编号
            raise_on_error: 是否遇到错误时抛出异常
        Returns:
            dict | None: 响应内容对象，出错时为None
        """
        device_id = self.device_id
        request_tag = self._generate_request_tag()
        url = f"{self.base_url}{self.api_path}"
        request_data = {"commodityNo": commodity_no}
        headers = {
            "host": "api.youpin898.com",
            "tracestate": "bnro=android/7.1.2_android/8.12.1_okhttp/3.14.9",
            "traceparent": "00-238741034b064bc4b8a1c01e0fa009ad-8945635009a928fb-01",
            "devicetoken": device_id,
            "deviceid": device_id,
            "requesttag": request_tag,
            "gameid": "730",
            "devicetype": "0",
            "platform": "android",
            "currenttheme": "Light",
            "package-type": "uuyp",
            "content-encoding": "gzip",
            "app-version": "5.29.2",
            # "uk": self.uk,
            "device-info": json.dumps({
                "deviceId": device_id,
                "deviceType": "SM-G988N",
                "hasSteamApp": 0,
                "requestTag": request_tag,
                "systemName": "Android",
                "systemVersion": "7.1.2"
            })
        }
        if self.auth_token:
            headers["authorization"] = self.auth_token
        if self.uk:
            headers["uk"] = self.uk
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(request_data, indent=2, ensure_ascii=False)}")
        try:
            response = requests.post(url, json=request_data, headers=headers)
            print("\n=== 响应信息 ===")
            try:
                resp_json = response.json()
            except Exception:
                resp_json = response.text
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False) if isinstance(resp_json, dict) else resp_json}")
            code_val = resp_json.get('Code', resp_json.get('code', -1)) if isinstance(resp_json, dict) else -1
            if code_val != 0:
                print(f"API返回错误: {resp_json.get('Msg', resp_json.get('msg', '未知错误')) if isinstance(resp_json, dict) else resp_json}")
                if raise_on_error:
                    raise Exception(f"业务处理失败: {resp_json.get('Msg', resp_json.get('msg')) if isinstance(resp_json, dict) else resp_json}")
                return None
            return resp_json
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            if raise_on_error:
                raise
            return None

# 使用示例
if __name__ == "__main__":
    # 授权令牌
    auth_token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI3MDU0NzI4MDkyNGI0NjYyYmQ0ZGEzMzQxYWExZTM5OSIsIm5hbWVpZCI6Ijk1MzQ1OTIiLCJJZCI6Ijk1MzQ1OTIiLCJ1bmlxdWVfbmFtZSI6IuWFqOWkqTgxNTkiLCJOYW1lIjoi5YWo5aSpODE1OSIsInZlcnNpb24iOiJjdVUiLCJuYmYiOjE3NDE0MjAwMDcsImV4cCI6MTc0NDU4MDgwNywiaXNzIjoieW91cGluODk4LmNvbSIsImRldmljZUlkIjoiWjdMZUg3dmREWWNEQUlZSTMvVFZYZkFIIiwiYXVkIjoidXNlciJ9.PMXsEg2PqnAroFikZKKUPdB1_I5h6hjgL1JzPHSUYso"
    
    # UK值
    uk = "5FDFSRFUD0wsn4vgzgeZpQIxPQzgCtMd3SfawJ2FStxg6MCO4d1esVBdyWoCfkr1N"
    
    # 设备ID
    device_id = "WjLFH7vdDY4DAIYI8/TVDYfAH"
    
    # 创建API实例
    api = LeaseVerifyApi(auth_token=auth_token, uk=uk, device_id=device_id)
    
    # 发送验证请求
    commodity_no = "123456"  # 示例商品编号
    response = api.send_verify(commodity_no)
    
    # 解析JSON响应并打印关键信息
    if response is not None:
        print("\n请求结果摘要:")
        print(f"代码: {response.get('code')}")
        print(f"消息: {response.get('msg')}")
